package chapter14.web;

import java.util.*;

import chapter14.core.*;

import chapter14.domain.*;

import chapter14.manager.*;

import com.softwarementors.extjs.djn.config.annotations.DirectFormPostMethod;
import com.softwarementors.extjs.djn.config.annotations.DirectMethod;

import org.apache.commons.fileupload.FileItem;


public class RoleAction extends SecurityAction<Role> {
    private RoleManager roleManager;
    private MenuManager menuManager;

    @Override
    protected RoleManager getEntityDao() {
        return roleManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public void setMenuManager(MenuManager menuManager) {
        this.menuManager = menuManager;
    }

    @DirectMethod
    public Object list() throws Exception {
        if (!this.check("Role")) {
            return this.failure();
        }

        return super.list();
    }

    @DirectFormPostMethod
    @Override
    public Object save(Map<String, String> param,
        Map<String, FileItem> files) throws Exception {
        if (!this.check("Role")) {
            return this.failure();
        }

        return super.save(param, files);
    }

    @Override
    protected void beforeSave(Role entity, Map<String, String> param)
        throws Exception {
        super.beforeSave(entity, param);

        entity.getMenus().clear();

        String menuList = param.get("menuList");

        for (String str : menuList.split(",")) {
            try {
                long menuId = Long.parseLong(str);
                Menu menu = menuManager.get(menuId);
                entity.getMenus().add(menu);
            } catch (Exception ex) {
                System.err.println(ex);
            }
        }
    }

    @DirectMethod
    @Override
    public Object remove(String ids) throws Exception {
        if (!this.check("Role")) {
            return this.failure();
        }

        return super.remove(ids);
    }
}
